#include <stdlib.h>
#include <stdio.h>
#include "cli.h"

void cmd_pwd(int sock, int sockmsg)
{
	char dirName[30];
	memset(dirName, '\0', sizeof(dirName));
	write(sockmsg, user_cmd, sizeof(user_cmd));
	read(sock, dirName, 30);
	printf("%s\n", dirName);
}

void cmd_dir(int sock, int sockmsg)
{
	int i, fileNum = 0;
	char fileInfo[50];

	write(sockmsg, user_cmd, sizeof(user_cmd));
	read(sock, &fileNum, sizeof(int));

	printf("-----------------------------------------------------------\n");
	printf("file number: %d\n", fileNum);
	if (fileNum > 0) {
		for (i = 0; i < fileNum; i++) {
			memset(fileInfo, '\0', sizeof(fileInfo));
			read(sock, fileInfo, sizeof(fileInfo));
			printf("%s\n", fileInfo);
		}
	}
}

void cmd_cd(int sock, int sockmsg, char *dirName)
{
	char currentDirPath[200];
	write(sockmsg, user_cmd, sizeof(user_cmd));
	write(sockmsg, cmd_arg, sizeof(cmd_arg));
	read(sock, currentDirPath, sizeof(currentDirPath));
}

void cmd_cdback(int sock, int sockmsg)
{
	write(sockmsg, user_cmd, sizeof(user_cmd));
}

void cmd_quit(int sock, int sockmsg)
{
	write(sockmsg, user_cmd, sizeof(user_cmd));
}

void cmd_help(int sock, int sockmsg)
{
	char help[300];
	write(sockmsg, user_cmd, sizeof(user_cmd));
	read(sock, help, sizeof(help));

	printf("%s\n", help);
}

void cmd_get(int sock, int sockmsg, char *fileName)
{
	int fd;
	long fileSize;
	char localFilePath[200];

	write(sockmsg, user_cmd, sizeof(user_cmd));
	write(sockmsg, cmd_arg, sizeof(cmd_arg));

	printf("%s\n%s\n", user_cmd, cmd_arg);

	memset(localFilePath, '\0', sizeof(localFilePath));
	getcwd(localFilePath, sizeof(localFilePath));
	strcat(localFilePath, "/");
	strcat(localFilePath, fileName);

	fd = open(localFilePath, O_RDWR | O_CREAT, S_IREAD | S_IWRITE);
	if (fd != -1) {
		memset(buf, 0, dataLen);
		read(sock, &fileSize, sizeof(long));

		while (fileSize > dataLen) {
			read(sock, buf, dataLen);
			write(fd, buf, dataLen);
			fileSize = fileSize - dataLen;
		}

		read(sock, buf, fileSize);
		write(fd, buf, fileSize);
		close(fd);
		printf("Download completed\n");
	}
	else {
		printf("Open file %s failed\n", localFilePath);
	}
}

void cmd_put(int sock, int sockmsg, char *fileName)
{
	int fd;
	long fileSize;
	char filePath[200];
	struct stat fileSta;

	write(sockmsg, user_cmd, sizeof(user_cmd));
	write(sockmsg, cmd_arg, sizeof(cmd_arg));

	memset(filePath, 0, sizeof(filePath));
	getcwd(filePath, sizeof(filePath));

	strcat(filePath, "/");
	strcat(filePath, fileName);

	fd = open(filePath, O_RDONLY, S_IREAD);
	if (fd != -1) {
		fstat(fd, &fileSta);
		fileSize = (long)fileSta.st_size;

		write(sock, &fileSize, sizeof(long));
		memset(buf, '\0', dataLen);

		while (fileSize > dataLen) {
			read(fd, buf, dataLen);
			write(sock, buf, dataLen);
			fileSize = fileSize - dataLen;
		}

		read(fd, buf, fileSize);
		write(sock, buf, fileSize);
		close(fd);
		printf("Upload completed\n");
	}
	else {
		printf("Open file %s failed\n", filePath);
	}
}
